package com.etc.filter;

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Order
@Component
@WebFilter(urlPatterns = "/admin/views/*", filterName = "loginFilter")
public class LoginFilter implements Filter {

    @Override
    public void destroy() {
        // TODO Auto-generated method stub

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        if (req.getSession().getAttribute("admin") != null) {
            chain.doFilter(req, res);
        } else {
            if (((HttpServletRequest) req).getServletPath().equals("/admin/views/login.jsp")) {
                chain.doFilter(req, res);
            } else {
                res.sendRedirect("/admin/views/login.jsp");
            }
        }

    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub

    }

}
